package cn.hnbjx.prepaid.service;

import cn.hnbjx.prepaid.common.BusinessException;
import cn.hnbjx.prepaid.common.BusinessStatus;
import cn.hnbjx.prepaid.dao.AccountDao;
import cn.hnbjx.prepaid.pojo.Account;
import cn.hnbjx.prepaid.pojo.WxParameter;
import cn.hnbjx.prepaid.utils.HttpRequestUtil;
import cn.hnbjx.prepaid.utils.JSONUtil;
import cn.hnbjx.prepaid.utils.ShareUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;

@Service
@Slf4j
public class WxService implements HandlerInterceptor {
    @Autowired
    private WxParameter wxParameter;
    @Autowired
    private AccountDao accountDao;
//    @Autowired
//    private Token token;

    @Autowired
    private HttpSession httpSession;

    public Map<String, Object> code2openId(String code) {
        String mpAppid = wxParameter.getmpAppId();
        String mpAppsecret = wxParameter.getMpAppSecret();
        String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + mpAppid
                + "&secret=" + mpAppsecret
                + "&code=" + code
                + "&grant_type=authorization_code";

        String response = HttpRequestUtil.sendGet(URL);

        Map<String, Object> map = JSONUtil.jsonToMap(response);

        if (map.get("openid") == null) {
            throw new BusinessException(BusinessStatus.FAIL, "OPENID获取失败：" + map.get("errmsg"));
        }
        return map;
    }

    public Account getMpAccountInfo(String openId, String nickName,String head) {

        if (null == accountDao.findAccountById(openId) || "".equals(accountDao.findAccountById(openId))) {
            Account account = new Account();
            account.setNickname(nickName);
            account.setHead(head);
            account.setOpenId(openId);
            accountDao.insert(account);
        }
        return accountDao.findAccountById(openId);
    }
}
